# -*- coding: utf-8 -*-
from odoo import http
import json, datetime, copy, urllib2, time, uuid
from odoo.addons.weixin.api.weixinapi import WeiXinApi
from odoo.addons.weixin.api.session_manager import session_obj
from odoo.addons.weixin.api.weixinapi import WeiXinApiObj
from odoo.exceptions import UserError
import logging

_loggle = logging.getLogger(__name__)


class WeixinController(http.Controller):

    @http.route('/wliot/weixin/login', type='http', auth='none', csrf=False)
    def wechat_login(self, **kw):
        '''微信登录 前端传入code 后端获取openid 检查该微信账号是否有绑定的账号 返回sessionid及绑定的状态'''
        try:
            _loggle.info('----weixin-login--------')
            code = kw.get('code', '')
            if not code:
                return json.dumps({
                    'data': '',
                    'success': False,
                    'code': 500,
                    'msg': u'请传入code！',
                })
            # 通过code验证微信号

            weixinAuthData = WeiXinApiObj.auth(code)
            # _loggle.info(u'weixinAuthData: %s' % str(weixinAuthData))
            open_id = weixinAuthData.get('openid', '')
            if not open_id:
                return json.dumps({
                    'data': '',
                    'success': False,
                    'code': 500,
                    'msg': u'获取openid失败！',
                })
            # 将sessioid放入redis
            session_id = str(uuid.uuid1())
            session_obj.pydis.set(session_id, open_id)
            # 检查有没有绑定的客户
            bind = False
            wechat_obj = http.request.env['weixin.user'].sudo()
            records = wechat_obj.search([
                ('open_id', '=', open_id),
            ])
            for rec in records:
                if rec.partner_id:
                    bind = True
                    break
            if bind:
                return json.dumps({
                    'session_id': session_id,
                    'success': True,
                    'bind': True,
                    'code': 0,
                    'msg': '',
                })
            else:
                return json.dumps({
                    'session_id': session_id,
                    'bind': False,
                    'code': 100,
                    'success': True,
                    'msg': u'未绑定账号！',
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'msg': error,
                })

    @http.route('/wliot/weixin/SendVerifyCode', auth='none', csrf=False)
    def wechat_send_verify_code(self, **kw):
        '''微信发送验证码'''
        try:
            phone = kw.get('phone')
            if not phone:
                return json.dumps({
                    'success': False,
                    'msg': u'请传入电话！',
                    'code': 400,
                })
            check_result = self.check_phone_legal(phone)
            if not check_result['success']:
                return json.dumps(check_result)
            send_result = http.request.env['phone.verify.wizard'].sudo().send_verify_code(phone)  # 发送验证码

            if not send_result['success']:
                return json.dumps(send_result)
            return json.dumps({
                'success': True,
                'msg': '',
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'msg': error,
                })

    @http.route('/wliot/weixin/CheckVerifyCode', type='http', auth='none', csrf=False)
    def wechat_check_verify_code(self, **kw):
        '''微信校验验证码 并绑定酒店'''
        try:
            # 校验session是否存在/过期
            session_id = kw.get('SessionID')
            if not session_id:
                return json.dumps({
                    'success': False,
                    'msg': u'请传入SessionID！',
                    'code': 400,
                })
            phone = kw.get('phone')
            if not phone:
                return json.dumps({
                    'success': False,
                    'msg': u'请填写电话！',
                    'code': 400,
                })
            code = kw.get('code')
            if not code:
                return json.dumps({
                    'success': False,
                    'msg': u'请填写验证码！',
                    'code': 400,
                })
            open_id = session_obj.pydis.get(session_id)
            if not open_id:
                return json.dumps({
                    'success': False,
                    'code': 900,
                    'msg': 'session过期！',
                })
            # 验证电话
            check_result = self.check_phone_legal(phone)
            if not check_result['success']:
                return json.dumps(check_result)
            customers = check_result['value']
            check_result = http.request.env['phone.verify.wizard'].sudo().check_mobile_verify_code(phone, code)  # 校验验证码
            if not check_result['success']:
                return json.dumps(check_result)
            # 绑定
            weixin_user_obj = http.request.env['weixin.user'].sudo()
            for customer in customers:
                wechat_user_rec = weixin_user_obj.search([
                    ('open_id', '=', open_id),
                    ('partner_id', '=', customer.id),
                ])
                if not wechat_user_rec:
                    weixin_user_obj.create({
                        'open_id': open_id,
                        'partner_id': customer.id,
                    })
            partner = http.request.env['res.partner'].sudo().search([
                '|',
                ('mobile', '=', phone),
                ('phone', '=', phone)
            ], limit=1)
            user = http.request.env['res.users'].sudo().search([
                ('partner_id', '=', partner.id)
            ])
            if partner.partner_type == 'mainuser':
                isMaintainor = True
            elif partner.partner_type == 'customer':
                isMaintainor = False
            if not user:
                return json.dumps({
                    'success': True,
                    'msg': '',
                    'isMaintainor': isMaintainor,
                    'name': partner.name,
                    'phone': phone
                })
            else:
                return json.dumps({
                    'success': True,
                    'msg': '',
                    'isMaintainor': isMaintainor,
                    'name': partner.name,
                    'phone': phone
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'msg': error,
                })

    @http.route('/wliot/weixin/queryLoginPermission', auth='none', csrf=False)
    def queryLoginPermission(self, **kw):
        ''' 验证登陆权限 '''
        try:
            phone = kw.get('phone')
            partners = http.request.env['res.partner'].sudo().search([
                '|',
                ('mobile', '=', phone),
                ('phone', '=', phone)
            ])
            if partners:
                # for partner in partners:
                #     user = http.request.env['res.users'].sudo().search([
                #         ('partner_id', '=', partner.id)
                #     ])
                #     if not user:
                #         http.request.env['res.users'].sudo().create({
                #             # 'name': partner.phone if partner.phone else partner.mobile,
                #             'partner_id': partner.id
                #         })
                return json.dumps({
                    'success': True,
                    'code': 200,
                    'message': u'该账号拥有登录权限！'
                })
            else:
                return json.dumps({
                    'success': False,
                    'code': 200,
                    'message': u'该账号没有登录权限！'
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })

    ########################################################################################################

    def get_beijing_today(self):
        '''获取北京时间的今天'''
        beijing_today = datetime.datetime.now() + datetime.timedelta(hours=8)
        beijing_today = beijing_today.strftime("%Y-%m-%d")
        return beijing_today

    def get_beijing_yestorday(self):
        '''获取北京时间的今天'''
        beijing_yestorday = datetime.datetime.now() + datetime.timedelta(hours=8) - datetime.timedelta(days=1)
        beijing_yestorday = beijing_yestorday.strftime("%Y-%m-%d")
        return beijing_yestorday

    def transform_date_str(self, datetime_str):
        '''将utc datetime 转化为北京时间 date'''
        beijing_datetime = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=8)
        beijing_date = beijing_datetime.strftime("%Y-%m-%d")
        return beijing_date

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner
        # customer_id_list = [rec.partner_id.id for rec in wechat_recs]
        # if not customer_id_list:
        #     return {
        #         'success': False,
        #         'code': 100,
        #         'msg': u'未绑定账号！',
        #     }
        # all_customer_id_list = customer_id_list[:]
        # partner_obj = http.request.env['res.partner'].sudo()
        # for customer_id in customer_id_list:
        #     partner = partner_obj.browse(customer_id)
        #     phone_list = []
        #     if partner.contact_person_phone:
        #         phone_list.append(partner.contact_person_phone)
        #     if partner.responsible_person_phone:
        #         phone_list.append(partner.responsible_person_phone)
        #     partner_recs = http.request.env['res.partner'].sudo().search([
        #         ('partner_type', '=', 'customer'),
        #         '|',
        #         ('contact_person_phone', 'in', phone_list),
        #         ('responsible_person_phone', 'in', phone_list),
        #     ])
        #     if partner_recs:
        #         all_customer_id_list += partner_recs.ids
        # all_customer_id_list = list(set(all_customer_id_list))
        # partners = partner_obj.browse(all_customer_id_list)
        #
        # customer_id = int(kw.get('customer_id', 0))
        # if customer_id:
        #     partner = partner_obj.browse(customer_id)
        # else:
        #     partner = partners[0]
        # return {
        #     'success': True,
        #     'partner': partner,
        #     'partners': partners,
        # }

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            '|',
            ('mobile', '=', phone),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }